""" Redis数据库初始化
@Project: Rebar
@File: init.py
@Author: hzc
@Date: 2023/3/22 13:03
"""
import aioredis
from fastapi import FastAPI
from aioredis import Redis
from config import REDIS_CONFIG


def redis_init(app: FastAPI):
    """
    项目启时初始化Redis
    :param app:
    :return:
    """

    async def get_redis_pool() -> Redis:
        """
        获取redis的连接池
        :return:
        """
        redis = await aioredis.from_url(**REDIS_CONFIG)
        return redis

    @app.on_event("startup")
    async def startup_event():
        app.state.redis = await get_redis_pool()
        print("redis已连接")

    @app.on_event("shutdown")
    async def shutdown_event():
        await app.state.redis.wait_closed()
        print("redis已断开连接")
